package com.catm.haitao.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;


import com.catm.haitao.widget.CustomWebView;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by taoweisong on 16/1/7.
 */

public abstract class BaseWebViewFragment extends Fragment {

    private static final String TAG = "BaseWebViewFragment";
    protected LayoutInflater mInflater;
    protected View mView;
    protected CustomWebView mWebView;
    protected ImageView mImgBg;
    ProgressBar topProgressBar;
    protected String cachedJsContent = "";

    private OnWebViewClientListener mOnWebViewClientListener;
    private OnWebChromeClientListener mOnWebChromeClientListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mInflater = inflater;
        mView = inflater.inflate(getResources().getIdentifier("moxie_client_fragment_webview", "layout", getActivity().getPackageName()), container, false);
        mWebView = (CustomWebView) mView.findViewById(getResources().getIdentifier("CustomWebView_Main", "id", getActivity().getPackageName()));
        mImgBg = (ImageView) mView.findViewById(getResources().getIdentifier("ImageView_Bg", "id", getActivity().getPackageName()));
        topProgressBar = (ProgressBar) mView.findViewById(getResources().getIdentifier("webview_top_progressbar", "id", getActivity().getPackageName()));
        topProgressBar.setProgress(0);

        //WebView设置;
        if (Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
            mWebView.getSettings().setMixedContentMode(0);
        }
        //WebView设置
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.clearCache(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");

        if (useWidePort()) {
            setUseWidePort();
        }

        int color = Color.parseColor("#ff9500");
        ClipDrawable d = new ClipDrawable(new ColorDrawable(color), Gravity.LEFT, ClipDrawable.HORIZONTAL);
        topProgressBar.setProgressDrawable(d);

        initWebview();

        return mView;
    }

    private void setUseWidePort() {
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
    }

    protected boolean useWidePort() {
        return false;
    }

    protected void setJsContent(String js){
        cachedJsContent = js;
    }

    /**
     * @param url
     */
    public void clearCookie(List<String> domains, String url) {

        try {
            if (domains != null && domains.size() > 0) {
                for (String domain : domains) {
                    clearCookieInternal(domain);
                }
            } else if (!TextUtils.isEmpty(url)) {
                clearCookieInternal(url);
            }
        } catch (Exception e){
        }
    }

    protected void clearCookieInternal(String url) {
        try {
            CookieSyncManager.createInstance(getActivity());
            CookieManager cm = CookieManager.getInstance();
            String cookieGlob = cm.getCookie(url);
            if (cookieGlob != null) {
                String[] cookies = cookieGlob.split(";");
                for (String cookieTuple : cookies) {
                    String[] cookieParts = cookieTuple.split("=");
                    cm.setCookie(url, cookieParts[0].trim()+"=; Expires=Wed, 31 Dec 1900 23:59:59 GMT");
                }
                cm.removeExpiredCookie();
                CookieSyncManager.getInstance().sync();
            }
        } catch (Exception e){
        }
    }

    private void initWebview() {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.setWebContentsDebuggingEnabled(true);
        }

        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                //增加进度条
                if (null != topProgressBar) {
                    topProgressBar.setVisibility(View.VISIBLE);
                    topProgressBar.setProgress(newProgress);
                }

                if (newProgress == 100 && null != topProgressBar) {
                    topProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                if (cm.messageLevel() == ConsoleMessage.MessageLevel.DEBUG) {
                    Log.d(TAG, String.format("%s -- From line %s of %s", cm.message(), cm.lineNumber(), cm.sourceId()));
                } else if (cm.messageLevel() == ConsoleMessage.MessageLevel.LOG || cm.messageLevel() == ConsoleMessage.MessageLevel.TIP) {
                    Log.d(TAG, String.format("%s -- From line %s of %s", cm.message(), cm.lineNumber(), cm.sourceId()));
                } else if (cm.messageLevel() == ConsoleMessage.MessageLevel.WARNING) {
                    Log.d(TAG, String.format("%s -- From line %s of %s", cm.message(), cm.lineNumber(), cm.sourceId()));
                } else if (cm.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
                    Log.d(TAG, String.format("%s -- From line %s of %s", cm.message(), cm.lineNumber(), cm.sourceId()));
                    if ("Uncaught ReferenceError: PGCallback is not defined".equals(cm.message())) {
                    }
                }
                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                try {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(message);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    });
                    builder.setCancelable(false).create().show();
                } catch (Exception e) {
                    try {
                        if (result != null)
                            result.confirm();
                    } catch (Exception ex){
                    }
                }
                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(mOnWebChromeClientListener!=null){
                    mOnWebChromeClientListener.onReceivedTitle(view, title);
                }
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {

            long startTime;
            long finishTime;
            long timeSpan;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d(TAG, "onPageStarted: " + url);
                if (mOnWebViewClientListener != null)
                    mOnWebViewClientListener.onPageStarted(view, url, favicon);
                startTime = new Date().getTime();
                Log.e(TAG, "onPageStarted start time="+startTime);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG, "onPageFinished : " + url);
                if(!TextUtils.isEmpty(cachedJsContent)){
                    postEvaluateJs(cachedJsContent);
                }
                if (mOnWebViewClientListener != null)
                    mOnWebViewClientListener.onPageFinished(view, url);
                finishTime = new Date().getTime();
                timeSpan = finishTime -startTime;
                Log.e(TAG, "onPageFinished time="+String.valueOf(timeSpan/1000f) +"秒");
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.d(TAG, "onReceivedError errorCode=" + errorCode + ",description=" + description + ",failingUrl=" + failingUrl);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (Uri.parse(url).getScheme().startsWith("file")) {
                    // 如果是本地加载的话，直接用当期浏览器加载
                    return false;
                }
                if (Uri.parse(url).getScheme().startsWith("http")) {
                    return false;
                }
                if ("about:blank".equals(url)) {
                    // 不需要处理空白页
                    return false;
                }

                if (mOnWebViewClientListener != null)
                    mOnWebViewClientListener.shouldOverrideUrlLoading(view, url);
                return true;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

                try {
                    if (mOnWebViewClientListener != null)
                        mOnWebViewClientListener.shouldInterceptRequest(view, url);
                } catch (Exception e) {
                }

                return null;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    String url = request.getUrl().toString();
////                    Log.e(TAG, "shouldInterceptRequest url=" +url);
//                    if(!isValidUrl(url)){
//                        return new WebResourceResponse(null, null, null);
//                    }
//                }
                return null;
            }

        });
    }

    private boolean isValidUrl(String url){
        if(whiteList.contains(url)) return true;
        if(url.contains(".png") || url.contains(".jpg") || url.contains(".webp") || url.contains("gif")) return false;
        return true;
    }

    static List<String> whiteList;

    static{
        whiteList = Arrays.asList(
            "https://misc.360buyimg.com/lib/img/e/blank.gif"
        );
    }


    public void setOnWebViewClientListener(OnWebViewClientListener onWebViewClientListener) {
        mOnWebViewClientListener = onWebViewClientListener;
    }

    public void setOnWebChromeClientListener(OnWebChromeClientListener onWebChromeClientListener) {
        mOnWebChromeClientListener = onWebChromeClientListener;
    }

    /**
     * 回退
     */
    public Boolean historyBack() {
        Boolean back = false;
        try {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                back = true;
            }
        } catch (Exception e) {

        } finally {
            return back;
        }
    }

    /**
     * 注入JS
     *
     * @param jsUrl
     */
    public void postEvaluateJs(final String jsUrl) {
        if (mWebView != null && !TextUtils.isEmpty(jsUrl)) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    if (mWebView != null) {
                        mWebView.loadUrl("javascript:" + jsUrl);
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.resumeTimers();
        }
    }

    @Override
    public void onDestroy() {
        try {
            if (mWebView != null) {
                ViewGroup parent = (ViewGroup) mWebView.getParent();
                if (parent != null) {
                    parent.removeView(mWebView);
                }
                mWebView.removeAllViews();
                mWebView.destroy();
                mWebView = null;
            }
            topProgressBar = null;
        } catch (Exception e) {
        }
        super.onDestroy();
    }

    public boolean isActive() {
        return isAdded();
    }

    public String getCachedJsContent() {
        return cachedJsContent;
    }

    public static class OnWebViewClientListener {
        public void onPageStarted(WebView view, String url, Bitmap favicon){}

        public void onPageFinished(WebView view, String url){}

        public boolean shouldOverrideUrlLoading(WebView view, String url){return false;}

        public void shouldInterceptRequest(WebView view, String url){}

        public boolean shouldInterceptRequest(WebView view, WebResourceRequest request){return false;}
    }

    public static class OnWebChromeClientListener{
        public void onReceivedTitle(WebView view, String title){}
    }
}
